package com.cy.pj.sys.controller;

import com.cy.pj.sys.pojo.User;
import com.cy.pj.sys.service.UserService;
import com.cy.pj.sys.util.JsonResult;
import org.apache.commons.lang3.StringUtils;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller
@RequestMapping("user")
public class UserController {
    private Logger logger = LogManager.getLogger(UserController.class);

@Autowired
    private UserService userService;

    /**
     * 登录系统
     *
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public JsonResult login(String userName, String password) {
        JsonResult result = new JsonResult();
        if (StringUtils.isBlank(userName)) {
            result.setResultCode(JsonResult.FAIL);
            result.setResultMsg("请输入用户名");
            return result;
        }

        if (StringUtils.isBlank(password)) {
            result.setResultCode(JsonResult.FAIL);
            result.setResultMsg("请输入密码");
            return result;
        }

        try {
            User user = userService.login(userName, password);
            result.setResultCode(JsonResult.SUCCESS);
            result.setResultMsg("登录成功");
            result.setResultContent(user);
        } catch (AuthenticationException e) {//如果抛出AuthenticationException异常，说明登录效验未通过
            result.setResultCode(JsonResult.FAIL);
            result.setResultMsg("用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("登录异常", e);
            result.setResultCode(JsonResult.FAIL);
            result.setResultMsg("登录异常");
        }

        return result;
    }
}
